package com.study.Link;

/**
 * - *@ClassName Joseph
 * - *@Author LiuHuaBing
 * - *@Date 2021/11/29 14:15
 * - *@Version 1.0
 * - 约瑟夫问题
 */
public class Joseph {

    /**
     * - @param num      单向环形链表数据个数
     * - @param startNum 开始节点
     * - @param k        偏移量
     */
    public static void addElement(int num, int startNum, int k) {
        UnidirectionalRingLinkList unidirectionalRingLinkList = new UnidirectionalRingLinkList();

        // 添加元素
        for (int i = 1; i <= num; i++) {
            unidirectionalRingLinkList.addElement(i);
        }
        unidirectionalRingLinkList.list();
        // 开始根据输入的开始位置 和移动量让数据有序出列
        // 单向链表删除数据需要记录当前节点的前一个节点 先找到第一个元素 和 最后一个元素
        Node first = unidirectionalRingLinkList.getFirst();
        Node helper;
        Node current = first;
        while (true) {
            if (current.next == first) {
                helper = current;
                break;
            }
            current = current.next;
        }
        current =first;
        // 根据起始坐标偏移完成
        for (int i = 0; i < startNum - 1; i++) {
            helper = helper.next;
            current = current.next;
        }
        while (current.next != current) {
            for (int i = 0; i < k - 1; i++) {
                helper = helper.next;
                current = current.next;
            }
            System.out.println(current.element + "移除环形链表");
            helper.next = current.next;
            current =current.next;
            if (current.next == current) {
                System.out.println("最后留下的数据是" + current.element);
                break;
            }
        }
    }

    public static void main(String[] args) {
        Joseph.addElement(25, 1, 2);

    }


}
